#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QtCore/QCoreApplication>
#include <QtCore/QTimer>
#include <QtGui/QSound>
#include <QtCore/QSettings>
#include <QtGui/QFileDialog>
#include <QtGui/QDesktopServices>
#include <QtCore/QFile>

int minutesForSliderPosition[] = { 0, 1, 2, 3, 4, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 90, 120, 150, 180, 210, 240 };

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent), ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    timer = new QTimer(this);
    timer->setInterval(200);
    connect(timer, SIGNAL(timeout()), this, SLOT(onTimer()));
    ui->horizontalSlider->setRange(0, (sizeof(minutesForSliderPosition)/sizeof(minutesForSliderPosition[0]))-1);
    alarmSoundFile = QSettings().value("Options/Alarm sound").toString();
    if (!QFile::exists(alarmSoundFile))
        on_pushButton_clicked();
    // Initialize the vibration.
    effect = new QFeedbackHapticsEffect(this);
    effect->setIntensity(1.0);
    effect->setDuration(1000);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::setOrientation(ScreenOrientation orientation)
{
#if defined(Q_OS_SYMBIAN)
    // If the version of Qt on the device is < 4.7.2, that attribute won't work
    if (orientation != ScreenOrientationAuto) {
        const QStringList v = QString::fromAscii(qVersion()).split(QLatin1Char('.'));
        if (v.count() == 3 && (v.at(0).toInt() << 16 | v.at(1).toInt() << 8 | v.at(2).toInt()) < 0x040702) {
            qWarning("Screen orientation locking only supported with Qt 4.7.2 and above");
            return;
        }
    }
#endif // Q_OS_SYMBIAN

    Qt::WidgetAttribute attribute;
    switch (orientation) {
#if QT_VERSION < 0x040702
    // Qt < 4.7.2 does not yet have the Qt::WA_*Orientation attributes
    case ScreenOrientationLockPortrait:
        attribute = static_cast<Qt::WidgetAttribute>(128);
        break;
    case ScreenOrientationLockLandscape:
        attribute = static_cast<Qt::WidgetAttribute>(129);
        break;
    default:
    case ScreenOrientationAuto:
        attribute = static_cast<Qt::WidgetAttribute>(130);
        break;
#else // QT_VERSION < 0x040702
    case ScreenOrientationLockPortrait:
        attribute = Qt::WA_LockPortraitOrientation;
        break;
    case ScreenOrientationLockLandscape:
        attribute = Qt::WA_LockLandscapeOrientation;
        break;
    default:
    case ScreenOrientationAuto:
        attribute = Qt::WA_AutoOrientation;
        break;
#endif // QT_VERSION < 0x040702
    };
    setAttribute(attribute, true);
}

void MainWindow::showExpanded()
{
#if defined(Q_OS_SYMBIAN) || defined(Q_WS_SIMULATOR)
    showFullScreen();
#elif defined(Q_WS_MAEMO_5)
    showMaximized();
#else
    show();
#endif
}

void MainWindow::onTimer()
{
    int seconds = QDateTime::currentDateTime().secsTo(targetDateTime);
    if (seconds < 0)
        seconds = 0;
    if (seconds == oldRemainingSeconds)
        return;
    oldRemainingSeconds = seconds;
    setLabelTextToSecs(seconds);
    if (!seconds) {
        timer->stop();
        ui->horizontalSlider->setValue(0);
        // Sound and vibration.
        effect->start();
        QSound::play(alarmSoundFile);
    }
}

void MainWindow::setLabelTextToSecs(int secs)
{
    if (secs / (60*60))
        ui->label->setText(QString("%1:%2:%3").arg(secs / (60*60), 2, 10, QChar('0')).arg((secs % (60*60)) / 60, 2, 10, QChar('0')).arg(secs % 60, 2, 10, QChar('0')));
    else
        ui->label->setText(QString("%2:%3").arg((secs % (60*60)) / 60, 2, 10, QChar('0')).arg(secs % 60, 2, 10, QChar('0')));
}

void MainWindow::on_pushButton_clicked()
{
    QString dir = alarmSoundFile;
    if (!QFile::exists(dir))
        dir = QDesktopServices::MusicLocation;
    QString newAlarmSound = QFileDialog::getOpenFileName(this, tr("Alarm sound"), dir, tr("Sounds (*.mp3 *.wav *.aac);;All Files (*.*)"));
    if (!newAlarmSound.isEmpty()) {
        alarmSoundFile = newAlarmSound;
        QSettings().setValue("Options/Alarm sound", newAlarmSound);
    }
}

void MainWindow::on_horizontalSlider_valueChanged(int value)
{
    timer->stop();
    setLabelTextToSecs(minutesForSliderPosition[value] * 60);
    if (!ui->horizontalSlider->isSliderDown())
        on_horizontalSlider_sliderReleased();
}

void MainWindow::on_horizontalSlider_sliderReleased()
{
    if (ui->horizontalSlider->value()) {
        oldRemainingSeconds = minutesForSliderPosition[ui->horizontalSlider->value()] * 60;
        targetDateTime = QDateTime::currentDateTime().addSecs(oldRemainingSeconds);
        timer->start();
    }
}
